package com.etong.frame.directive.impl.database;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.etong.frame.directive.util.CommonStatus;

public class DatabaseInsert extends DatabaseDirective {

	protected String fieldsConst = "";
	protected String valuesConst = "";

	protected StringBuilder frontBuilder;
	protected StringBuilder valuesBuilder;
	protected StringBuilder insertBuilder;

	protected String getBuilderStart() {
		return "Insert into ";
	}

	public DatabaseInsert(Statement statement) {
		super(statement);
	}

	public String getFieldsConst() {
		return fieldsConst;
	}

	public void setFieldsConst(String fieldsConst) {
		this.fieldsConst = fieldsConst;
	}

	public String getValuesConst() {
		return valuesConst;
	}

	public void setValuesConst(String valuesConst) {
		this.valuesConst = valuesConst;
	}

	protected boolean buildFields(String fields, String values) {

		List<String> fieldSplices = resolveFieldsConfig(fields);
		List<String> valueSplices = resolveFieldsConfig(values);

		for (int i = 0; i < fieldSplices.size(); i++) {
			String fieldExpr = fieldSplices.get(i);
			String valueExpr = valueSplices.get(i);

			Field field = createTableField(fieldExpr, BUILD_INSERT);
			field.createValue(valueExpr);
			// 将字段中变量添加全局变量中
			addPlaceholders(field.getPlaceholders());
			// 将字段添加列表中
			addTableField(field);
		}

		if (getTableFields().size() != valueSplices.size()) {
			logger.info("Fields and values size no match?"
					+ getTableFields().size() + ":" + valueSplices.size());
			return false;
		}
		return true;
	}

	public String reomveFirstDot(String source) {

		return source;
	}

	@Override
	public boolean buildConst(Statement op) {
		String fieldsExpr = getStatement().getTable_fields();
		String valuesExpr = getStatement().getTable_values();
		String tableName = getStatement().getTable_name();

		// 组建字段列表
		if (!buildFields(fieldsExpr, valuesExpr)) {
			logger.error("Build insert fields error");
			return false;
		}

		// 前置表达式
		frontBuilder = new StringBuilder(256);
		frontBuilder.append(getBuilderStart()).append(tableName).append("(");
		// 值表达式
		valuesBuilder = new StringBuilder(256);
		valuesBuilder.append(") VALUES(");

		// 用于返回完整的配置
		insertBuilder = new StringBuilder(256);
		StringBuilder valuesConfigBuilder = new StringBuilder(256);
		insertBuilder.append(frontBuilder);
		valuesConfigBuilder.append(valuesBuilder);

		for (Field field : getTableFields()) {
			if (!field.isReplaced()) {
				// 添加字段信息
				frontBuilder.append(field.getName()).append(DOT);
				valuesBuilder.append(field.getValue()).append(DOT);
			}

			insertBuilder.append(field.getName()).append(DOT);
			valuesConfigBuilder.append(field.getValue()).append(DOT);
		}

		buildComplete();

		insertBuilder.append(valuesConfigBuilder).append(")");

		return true;
	}

	protected void buildComplete() {
		logger.info("Build fields : " + JSON.toJSONString(getTableFields()));
		logger.info("Build insert:" + getStatement().getName() + "->"
				+ frontBuilder.toString() + valuesBuilder.toString() + ")");
	}

	@Override
	protected CommonStatus buildVariable(Map<String, Object> vars) {

		CommonStatus status = new CommonStatus();

		// 开始组装sql
		StringBuilder builder = new StringBuilder(256);
		builder.append(frontBuilder);
		StringBuilder temp = new StringBuilder(256);
		temp.append(valuesBuilder);

		boolean haveFields = false;
		for (Field field : getTableFields()) {
			// 判断是否需要进行替换的变量字段
			if (field.isReplaced()) {
				String fieldValue = field.getValue();
				String fieldName = field.getName();
				// 如果字段是必须的，但不存在该变量
				boolean fieldValid = true;
				for (Placeholder placeholder : field.getPlaceholders()) {
					if (!vars.containsKey(placeholder.getName())) {
						fieldValid = false;
					}
				}

				if (fieldValid) {
					builder.append(fieldName).append(DOT);
					temp.append(fieldValue).append(DOT);
					haveFields = true;
				} else {
					if (field.isRequired()) {
						logger.error("Required param no set :" + fieldValue);
						status.error(CommonStatus.DIRECTIVE_CREATE_ERROR,
								"Required param no set:" + fieldValue);
						return status;
					}
				}
			}
		}

		// 去掉最后结束的DOT
		if (haveFields) {
			builder = builder.deleteCharAt(builder.length() - 1);
			temp = temp.deleteCharAt(temp.length() - 1);
		}

		builder.append(temp).append(")");
		status.setObject(builder.toString());

		return status;
	}

	public String getStatementConfig() {
		return insertBuilder.toString();
	}
}
